import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
    {
      path: '/',
      component: () => import('../views/Login'),
    },
    {
      path: '/login',
      name: 'login',
      component:() => import('../views/Login')
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/Home'),
      redirect: '/novel_list',
      children: [
        {
          //小说列表
          path: '/novel_list',
          name: 'novel_list',
          component: () => import('../views/Novel_List/Novel_List')
        }, {
          //小说章节
          path: '/novel_diversity',
          name: 'novel_diversity',
          component: () => import('../views/Novel_List/novel_diversity')
        }, {
          //小说章节
          path: '/novel_details',
          name: 'novel_details',
          component: () => import('../views/Novel_List/novel_details')
        },
        {
          //小说章节详情
          path: '/novel_chapters',
          name: 'novel_chapters',
          component: () => import('../views/Novel_List/novel_chapters')
        },
        // 打赏
        {
          path: '/musang',
          name: 'musang',
          component: () => import('../views/Financial/musang')
        },{
          path: '/submit',
          name: 'submit',
          component: () => import('../views/Financial/submit')
        },
        {
          path: '/Novel_Comments',
          name: 'Novel_Comments',
          component: () => import('../views/comment/Novel_Comments')
        },{
          path:'/withdraw',
          name:'withdraw',
          component:()=>import('../views/withdraw/withdraw')
        },{
          path:'/baseInfo',
          name:'baseInfo',
          component:()=>import('../views/baseInfo/baseInfo')
        }
      ]
    },
    {
      path: '/404',
      component:
        () => import('../views/404'),
    },
    {
      path: '*', redirect:
        '/404',
    }
  ]
;

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/') {
    next();
    return
  }
  const tokenStr = sessionStorage.getItem('token');
  if (!tokenStr) {
    // 从URL查询参数中获取token
    // 获取当前页面的 host 部

// 获取查询字符串，即 URL 中 '?' 后面的部分
    const queryString = window.location.href;
    console.log('url:',queryString)
// 提取 token 参数。假设 token 是查询字符串中的一个参数
    let tokenStr = queryString.split('token=')
    if (tokenStr.length < 2) {
      return;
    }

    const token = tokenStr[1];
    console.log('token:',token)
    sessionStorage.setItem("token", token);

  }

  next();
});

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};


export default router
